import api from '../../../services/api'
var app = getApp();
Page({
  data: {
    baseInfo: {},
    /**选择车辆型号开始 */
    carModelCols: [{
      values: [],
      className: '品牌',
    },
    {
      values: [],
      className: '型号',
    },],
    carBrandId: "",
    carBrandName: "",
    carSeriesId: "",
    carSeriesName: "",
    showCarPopup: false,
    brandList: [],
    seriesData: {},
    carModelType: "",
    /**选择车辆型号结束 */

    /**选择产品 开始*/
    productCols: [{
      values: [],
      className: '产品',
    }],
    productId: "",
    productName: "",
    productSeriesId: "",
    productSeriesName: "",
    showProductPopup: false,
    productList: [],
    productSeriesData: {},
    /**选择产品 结束*/

    showDatePopup: false,
    defaultDate: new Date().getTime(),
    constructionDate: "",
    phone: "",
    productInfoList: [
      {
        signalId: "", // 卷芯码ID，用于提交
        xsxx: "" // 标签信息，用于显示
      }
    ],
    checkIndex: 0,
    mergedQrPicture: "",
    pictureList: [],
    qxImgList: [], // 清晰卷号图列表
    mdImg: "", // 车辆与店招图
  },
  onLoad: function () {
    this.queryBrandList();
    this.queryProductList();
  },
  onShow() {
  },
  goBack() {
    wx.navigateBack();
  },
  /***选择车型 开始****/
  openCarPopup: function (e) {
    const { carBrandName } = this.data;
    const carModelType = e.currentTarget.dataset.type;
    if (carModelType == '1' && !carBrandName) {
      wx.showToast({
        title: "请先选择品牌",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    this.setData({ showCarPopup: true, carModelType });
  },
  bindKeyInput (e) {
    console.log(e)
    if (e.currentTarget.dataset.name === 'productBatch') {
      this.data.productInfoList[e.currentTarget.dataset.index].productBatch = e.detail.value
    } else if (e.currentTarget.dataset.name === 'productBox') {
      this.data.productInfoList[e.currentTarget.dataset.index].productBox = e.detail.value
    } else if (e.currentTarget.dataset.name === 'signalId') {
      this.data.productInfoList[e.currentTarget.dataset.index].signalId = e.detail.value
    } else {
      return
    }
    this.setData({
      productInfoList: this.data.productInfoList
    })
  },
  onProductConfirm(event) {
    console.log(event)
    const { picker, value, index } = event.detail;
    const { productSeriesData } = this.data;
    this.data.productInfoList[this.data.checkIndex].productModel = value[0]
    this.setData({
      productInfoList: this.data.productInfoList,
      showProductPopup: false
    });
  },
  addProduct () {
    if (this.data.productInfoList.length > 3) {
      wx.showToast({
        title: "只能添加4个",
        icon: "error",
        duration: 2000,
      });
      return
    }
    this.data.productInfoList.push(
      {
        signalId: "",
        xsxx: ""
      }
    )
    this.setData({
      productInfoList: this.data.productInfoList
    })
    
    // 提示用户需要上传对应数量的清晰卷号图
    const productCount = this.data.productInfoList.length;
    if (this.data.qxImgList.length < productCount) {
      wx.showToast({
        title: `请注意：需要上传${productCount}张清晰卷号图`,
        icon: "none",
        duration: 2000,
      });
    }
  },
  removeProduct (e) {
    this.data.productInfoList.splice(e.currentTarget.dataset.index, 1)
    
    // 如果清晰卷号图数量超过产品数量，则删除多余的图片
    const productCount = this.data.productInfoList.length;
    if (this.data.qxImgList.length > productCount) {
      const newQxImgList = this.data.qxImgList.slice(0, productCount);
      this.setData({
        productInfoList: this.data.productInfoList,
        qxImgList: newQxImgList
      });
    } else {
      this.setData({
        productInfoList: this.data.productInfoList
      });
    }
  },
  onCarCancel() {
    this.setData({ showCarPopup: false });
  },
  onCarModelConfirm(event) {
    const { carModelCols, seriesData, brandList, carModelType } = this.data;
    const { value, index } = event.detail;
    if (carModelType == "0") {
      const { brandId, brandName } = brandList.find(item => item.brandName === value) || {};
      this.setData({
        carBrandId: brandId,
        carBrandName: brandName,
      });

      let columnValues = [];
      if (seriesData[value] && seriesData[value].length > 0) {
        columnValues = seriesData[value].map(item => item.seriesName)
      } else {
        this.querySeriesList().then(data => {
          columnValues = data.map(item => item.seriesName);
        });
      }
      carModelCols[1].values = columnValues;
      this.setData({
        showCarPopup: false,
        carModelCols
      });
    }
    if (carModelType == "1") {
      const { carBrandName } = this.data;
      this.setData({
        carSeriesId: seriesData[carBrandName][index].id,
        carSeriesName: value,
        showCarPopup: false
      });
    }
  },
  async queryBrandList() {
    const { carModelCols } = this.data;
    const res = await api.quote.queryBrandList();
    if (res.status == 200 && res.data && res.data.length > 0) {
      const carBrandNames = res.data.map(item => item.brandName);
      carModelCols[0].values = carBrandNames;
      this.setData({
        brandList: res.data,
        carModelCols,
      });
    }
  },
  async querySeriesList() {
    const { carBrandId, carBrandName, carModelCols, seriesData } = this.data;
    const res = await api.quote.queryCarModelList({ brandId: carBrandId });
    if (res.status == 200) {
      carModelCols[1].values = res.data.map(item => item.seriesName);
      seriesData[carBrandName] = res.data;
      this.setData({ carModelCols, seriesData });
    }
    return res.data || [];
  },

  /***选择车型 结束****/

  /***选择产品 开始****/
  openProductPopup(e) {
    this.setData({
      showProductPopup: true,
      checkIndex: e.currentTarget.dataset.index
    });
  },
  onProductCancel() {
    this.setData({ showProductPopup: false });
  },
  onProductChange(event) {
    const { productCols, productSeriesData, productList } = this.data;
    const { picker, value, index } = event.detail;
    if (index === 1) {
      return;
    }
    const { productId, productName } = productList.find(item => item.productName === value[0]) || {};
    this.setData({
      productId: productId,
      productName: productName,
    });
    let columnValues = productSeriesData[value[0]];
    if (columnValues && columnValues.length > 0) {
      picker.setColumnValues(1, columnValues.map(item => item.productSeries));
    } else {
      this.queryProductSeriesList().then(data => {
        picker.setColumnValues(1, data.map(item => item.productSeries));
      });
    }
  },
  async queryProductList() {
    const { productCols } = this.data;
    const res = await api.quote.queryProductList({ type: "1" });
    if (res.status == 200 && res.data && res.data.length > 0) {
      const names = res.data.map(item => item.productName);
      productCols[0].values = names;
      this.setData({
        productList: res.data,
        productCols,
      });
      // this.setData({
      //   productList: res.data,
      //   productCols,
      //   productId: res.data[0].productId,
      //   productName: res.data[0].productName
      // });
      // this.queryProductSeriesList();
    }
  },
  async queryProductSeriesList() {
    const { productId, productName, productCols, productSeriesData } = this.data;
    const res = await api.warrantyApi.queryProductSeriesList({ productId: productId });
    if (res.status == 200) {
      productCols[1].values = res.data.map(item => item.productSeries);
      productSeriesData[productName] = res.data;
      this.setData({ productCols, productSeriesData });
    }
    return res.data || [];
  },

  /***选择产品 结束****/

  /*** 选择时间开始****/
  showDatePopup() {
    this.setData({ showDatePopup: true });
  },
  onDateCancel() {
    this.setData({ showDatePopup: false });
  },
  
  formatDate(date) {
    if (typeof date === 'string') {
      date = new Date(date);
    } else if (typeof date === 'number') {
      date = new Date(date);
    }
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    
    return `${year}-${month}-${day}`;
  },
  
  onDateConfirm: function (e) {
    const formattedDate = this.formatDate(e.detail);
    this.setData({
      constructionDate: formattedDate,
      defaultDate: e.detail,
      showDatePopup: false
    });
  },

  /*** 选择时间结束****/
  checkForm(formData) {
    // 检查车主信息
    if (!formData.userName) {
      wx.showToast({
        title: "请输入车主姓名",
        icon: "none",
        duration: 1500,
      });
      return false;
    }
    
    if (!formData.phone) {
      wx.showToast({
        title: "请输入手机号",
        icon: "none",
        duration: 1500,
      });
      return false;
    }
    
    if (!(/^1[345789]\d{9}$/.test(formData.phone))) {
      wx.showToast({
        title: "请输入正确的手机号",
        icon: "none",
        duration: 1500,
      });
      return false;
    }
    
    // 检查车辆信息
    if (!this.data.carBrandName) {
      wx.showToast({
        title: "请选择车辆品牌",
        icon: "none",
        duration: 1500,
      });
      return false;
    }
    
    if (!this.data.carSeriesName) {
      wx.showToast({
        title: "请选择车辆型号",
        icon: "none",
        duration: 1500,
      });
      return false;
    }
    
    if (!formData.frameNumber) {
      wx.showToast({
        title: "请输入车架号",
        icon: "none",
        duration: 1500,
      });
      return false;
    }
    
    // 检查产品信息 - 验证卷芯码是否选择
    if (this.data.productInfoList.length === 0) {
      wx.showToast({
        title: "请至少添加一个产品信息",
        icon: "none",
        duration: 1500,
      });
      return false;
    }
    
    for (let i = 0; i < this.data.productInfoList.length; i++) {
      if (!this.data.productInfoList[i].signalId) {
        wx.showToast({
          title: `请选择第${i + 1}个产品的卷芯码`,
          icon: "none",
          duration: 1500,
        });
        return false;
      }
    }
    
    // 检查卷芯码是否有重复
    const signalIds = this.data.productInfoList.map(item => item.signalId).filter(id => id);
    const uniqueSignalIds = [...new Set(signalIds)];
    if (signalIds.length !== uniqueSignalIds.length) {
      wx.showToast({
        title: "卷芯码不能重复选择",
        icon: "none",
        duration: 1500,
      });
      return false;
    }
    
    // 检查施工信息
    if (!formData.position) {
      wx.showToast({
        title: "请输入施工部位",
        icon: "none",
        duration: 1500,
      });
      return false;
    }
    
    if (!this.data.constructionDate) {
      wx.showToast({
        title: "请选择施工时间",
        icon: "none",
        duration: 1500,
      });
      return false;
    }
    
    if (!formData.vehiclePrice) {
      wx.showToast({
        title: "请输入产品价格",
        icon: "none",
        duration: 1500,
      });
      return false;
    }
    
    // 检查图片上传
    if (!this.data.mergedQrPicture) {
      wx.showToast({
        title: "请上传车架号/卷芯码合拍图",
        icon: "none",
        duration: 1500,
      });
      return false;
    }
    
    if (this.data.pictureList.length === 0) {
      wx.showToast({
        title: "请上传装贴效果图",
        icon: "none",
        duration: 1500,
      });
      return false;
    }
    
    // 检查清晰卷号图
    const productCount = this.data.productInfoList.length;
    if (this.data.qxImgList.length !== productCount) {
      wx.showToast({
        title: `请上传${productCount}张清晰卷号图，当前已上传${this.data.qxImgList.length}张`,
        icon: "none",
        duration: 1500,
      });
      return false;
    }
    
    // 检查车辆与店招图
    if (!this.data.mdImg) {
      wx.showToast({
        title: "请上传车辆与店招图",
        icon: "none",
        duration: 1500,
      });
      return false;
    }
    
    return true;
  },
  async bindSave(e) {
    const formData = e.detail.value;
    if (!this.checkForm(formData)) return;
    
    // 处理表单数据，确保卷芯码字段使用signalId
    const processedFormData = { ...formData };
    this.data.productInfoList.forEach((item, index) => {
      processedFormData[`signalId${index}`] = item.signalId;
    });
    
    const { productName } = this.data;
    const postData = {
      ...processedFormData,
      productModel: productName,
      signalIdInfo: this.data.productInfoList.map(item => item.signalId).join(','),
      mergedQrPicture: this.data.mergedQrPicture,
      pictureList: this.data.pictureList.join('|'),
      qxImgList: this.data.qxImgList.join('|'),
      mdImg: this.data.mdImg
    };
    console.log(postData)
    const res = await api.warranty.addWarrantyInfo(postData);
    if (res.status == 200) {
      wx.showToast({
        title: "录入成功",
        icon: "none",
        duration: 1000,
      });
      const { phone } = postData;
      this.setData({ phone });
      this.queryWarrantyInfo();
    } else {
      wx.showToast({
        title: res.message,
        icon: "error",
        duration: 2000,
      });
    }
  },
  async queryWarrantyInfo() {
    const { phone } = this.data;
    const res = await api.warranty.queryWarrantyInfo({ phone });
    if (res.status == 200) {
      let product = {};
      const { ppfList, ...restData } = res.data;
      if (ppfList && ppfList.length > 0) {
        product = ppfList[0];
      }
      this.setData({ baseInfo: { ...restData, ...product } });
      wx.redirectTo({
        url: '/pages/warranty/query/index?phone=' + phone
      })
    }
  },
  scanFrame () {
    let _that = this
    wx.chooseImage({
      count: 1,  // 只允许选择一张图片
      sizeType: ['original', 'compressed'], // 可以选择原图或压缩图
      sourceType: ['camera', 'album'], // 直接调用相机
      success(res) {
        const tempFilePath = res.tempFilePaths[0]; // 获取拍摄的照片路径
        // 上传照片并调用OCR识别
        _that.recognizeVIN(tempFilePath);
      }
    })
  },
  async recognizeVIN(imagePath) {
    const res = await api.warranty.uploadFile(imagePath, 'VIN_OCR');
    if (res.status == 200) {
      this.queryVin(res.data.filePath)
    }
  },
  async queryVin (imgUrl) {
    const postData = {
      picture: imgUrl
    };
    const res = await api.warranty.queryVin(postData);
    if (res.status == 200) {
      this.setData({
        'baseInfo.frameNumber': res.data
      })
    }
  },
  goPage (e) {
    const url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: `${url}`,
    });
  },
  chooseQrImage() {
    const that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['camera', 'album'],
      success(res) {
        const tempFilePath = res.tempFilePaths[0];
        that.uploadQrImage(tempFilePath);
      }
    });
  },
  async uploadQrImage(filePath) {
    wx.showLoading({
      title: '上传中...'
    });
    
    try {
      const res = await api.warranty.uploadFile(filePath, 'KSG_PIC');
      if (res.status === 200 && res.data && res.data.filePath) {
        this.setData({
          mergedQrPicture: res.data.filePath
        });
        wx.showToast({
          title: '上传成功',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('上传车架号/卷芯码图失败:', error);
      wx.showToast({
        title: '上传失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },
  previewQrImage() {
    if (this.data.mergedQrPicture) {
      wx.previewImage({
        current: this.data.mergedQrPicture,
        urls: [this.data.mergedQrPicture]
      });
    }
  },
  deleteQrImage() {
    wx.showModal({
      title: '提示',
      content: '确定要删除这张图片吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            mergedQrPicture: ''
          });
        }
      }
    });
  },
  chooseEffectImages() {
    const that = this;
    const remainingCount = 9 - this.data.pictureList.length;
    
    wx.chooseImage({
      count: remainingCount,
      sizeType: ['original', 'compressed'],
      sourceType: ['camera', 'album'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        that.uploadEffectImages(tempFilePaths);
      }
    });
  },
  async uploadEffectImages(filePaths) {
    wx.showLoading({
      title: '上传中...'
    });
    
    try {
      const uploadPromises = filePaths.map(filePath => 
        api.warranty.uploadFile(filePath, 'SIGNAL_PIC')
      );
      
      const results = await Promise.all(uploadPromises);
      const successUrls = [];
      
      results.forEach(res => {
        if (res.status === 200 && res.data && res.data.filePath) {
          successUrls.push(res.data.filePath);
        }
      });
      
      if (successUrls.length > 0) {
        const newPictureList = [...this.data.pictureList, ...successUrls];
        this.setData({
          pictureList: newPictureList
        });
        
        wx.showToast({
          title: `上传成功${successUrls.length}张`,
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('上传装贴效果图失败:', error);
      wx.showToast({
        title: '上传失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },
  previewEffectImage(e) {
    const index = e.currentTarget.dataset.index;
    const current = this.data.pictureList[index];
    
    wx.previewImage({
      current: current,
      urls: this.data.pictureList
    });
  },
  deleteEffectImage(e) {
    const index = e.currentTarget.dataset.index;
    
    wx.showModal({
      title: '提示',
      content: '确定要删除这张图片吗？',
      success: (res) => {
        if (res.confirm) {
          const newPictureList = [...this.data.pictureList];
          newPictureList.splice(index, 1);
          this.setData({
            pictureList: newPictureList
          });
        }
      }
    });
  },
  /**
   * 选择卷芯码
   */
  selectStock(e) {
    const index = e.currentTarget.dataset.index
    wx.navigateTo({
      url: `./stock-select/index?index=${index}`
    })
  },

  /**
   * 卷芯码选择回调
   * @param {Object} stockItem 选中的库存项 {signalId: '卷芯码', xsxx: '标签信息'}
   * @param {Number} index 索引
   */
  onStockSelected(stockItem, index) {
    if (index >= 0 && index < this.data.productInfoList.length) {
      // 检查是否已经选择过相同的卷芯码
      const existingIndex = this.data.productInfoList.findIndex((item, i) => 
        i !== index && item.signalId === stockItem.signalId
      );
      
      if (existingIndex !== -1) {
        wx.showToast({
          title: `该卷芯码已在第${existingIndex + 1}个产品中使用`,
          icon: "none",
          duration: 2000,
        });
        return;
      }
      
      this.data.productInfoList[index].signalId = stockItem.signalId
      this.data.productInfoList[index].xsxx = stockItem.xsxx
      
      this.setData({
        productInfoList: this.data.productInfoList
      })
      
      wx.showToast({
        title: '卷芯码选择成功',
        icon: 'success',
        duration: 1000
      });
    }
  },
  
  /**
   * 提交表单（手动收集数据）
   */
  submitForm() {
    console.log('submitForm triggered')
    
    // 获取页面中的form元素并手动触发submit事件
    const query = wx.createSelectorQuery()
    query.select('#warrantyForm').fields({
      properties: ['value']
    }, (res) => {
      console.log('Form query result:', res)
    })
    query.exec()
    
    // 手动收集表单数据 - 从当前data中获取最新值
    const formData = {
      userName: this.data.baseInfo.userName || '',
      phone: this.data.baseInfo.phone || '',
      vehicleBrand: this.data.carBrandName || '',
      vehicleModel: this.data.carSeriesName || '',
      frameNumber: this.data.baseInfo.frameNumber || '',
      licensePlate: this.data.baseInfo.licensePlate || '',
      position: this.data.baseInfo.position || '',
      constructionDate: this.data.constructionDate || '',
      vehiclePrice: this.data.baseInfo.vehiclePrice || ''
    };
    
    console.log('Form data collected:', formData);
    
    // 模拟form submit事件
    const e = {
      detail: {
        value: formData
      }
    };
    
    // 调用原有的bindSave方法
    this.bindSave(e);
  },
  /**
   * 处理基础信息输入
   */
  onBaseInfoInput(e) {
    const { field } = e.currentTarget.dataset
    const value = e.detail.value
    
    this.setData({
      [`baseInfo.${field}`]: value
    })
  },
  // 清晰卷号图相关方法
  chooseQxImages() {
    const that = this;
    const currentCount = this.data.qxImgList.length;
    const productCount = this.data.productInfoList.length;
    const remainingCount = productCount - currentCount;
    
    if (remainingCount <= 0) {
      wx.showToast({
        title: '清晰卷号图数量已达到产品数量上限',
        icon: 'none'
      });
      return;
    }
    
    wx.chooseImage({
      count: remainingCount,
      sizeType: ['original', 'compressed'],
      sourceType: ['camera', 'album'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        that.uploadQxImages(tempFilePaths);
      }
    });
  },
  async uploadQxImages(filePaths) {
    wx.showLoading({
      title: '上传中...'
    });
    
    try {
      const uploadPromises = filePaths.map(filePath => 
        api.warranty.uploadFile(filePath, 'QX_IMG')
      );
      
      const results = await Promise.all(uploadPromises);
      const successUrls = [];
      
      results.forEach(res => {
        if (res.status === 200 && res.data && res.data.filePath) {
          successUrls.push(res.data.filePath);
        }
      });
      
      if (successUrls.length > 0) {
        const newQxImgList = [...this.data.qxImgList, ...successUrls];
        this.setData({
          qxImgList: newQxImgList
        });
        
        wx.showToast({
          title: `上传成功${successUrls.length}张`,
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('上传清晰卷号图失败:', error);
      wx.showToast({
        title: '上传失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },
  previewQxImage(e) {
    const index = e.currentTarget.dataset.index;
    const current = this.data.qxImgList[index];
    
    wx.previewImage({
      current: current,
      urls: this.data.qxImgList
    });
  },
  deleteQxImage(e) {
    const index = e.currentTarget.dataset.index;
    
    wx.showModal({
      title: '提示',
      content: '确定要删除这张图片吗？',
      success: (res) => {
        if (res.confirm) {
          const newQxImgList = [...this.data.qxImgList];
          newQxImgList.splice(index, 1);
          this.setData({
            qxImgList: newQxImgList
          });
        }
      }
    });
  },
  // 车辆与店招图相关方法
  chooseMdImage() {
    const that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['camera', 'album'],
      success(res) {
        const tempFilePath = res.tempFilePaths[0];
        that.uploadMdImage(tempFilePath);
      }
    });
  },
  async uploadMdImage(filePath) {
    wx.showLoading({
      title: '上传中...'
    });
    
    try {
      const res = await api.warranty.uploadFile(filePath, 'MD_IMG');
      if (res.status === 200 && res.data && res.data.filePath) {
        this.setData({
          mdImg: res.data.filePath
        });
        wx.showToast({
          title: '上传成功',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('上传车辆与店招图失败:', error);
      wx.showToast({
        title: '上传失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },
  previewMdImage() {
    if (this.data.mdImg) {
      wx.previewImage({
        current: this.data.mdImg,
        urls: [this.data.mdImg]
      });
    }
  },
  deleteMdImage() {
    wx.showModal({
      title: '提示',
      content: '确定要删除这张图片吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            mdImg: ''
          });
        }
      }
    });
  },
});
